/**
 * @file 剪贴板相关
 */

/**
 * 复制文本数据到剪贴板
 * @param {string} text
 * @returns {Promise<void>} 返回一个promise，resolve即为成功
 *
 * @example
 * copyTextToClipboard('xxx')
 *   .then(()=>{ console.log('成功') })
 *   .catch(()=>{ console.log('失败') })
 */
export const copyTextToClipboard = text =>
  new Promise((resolve, reject) => {
    const url = text
    const textarea = document.createElement('textarea')
    const currentFocus = document.activeElement
    document.body.appendChild(textarea)
    textarea.value = url
    textarea.focus()
    if (textarea.setSelectionRange) {
      textarea.setSelectionRange(0, textarea.value.length)
    } else {
      textarea.select()
    }
    try {
      document.execCommand('copy')
      resolve()
    } catch (err) {
      reject()
    }
    document.body.removeChild(textarea)
    currentFocus.focus()
  })
